<?php

/**
 * @user magein
 * @date 2023/12/1 11:58
 */

namespace magein\sms;


use magein\sms\platform\Ali;
use magein\sms\platform\Platform;

class Factory
{
    /**
     * @throws SmsException
     */
    public static function make($config, $data): Platform
    {
        if (empty($config)) {
            SmsException::json('配置文件错误', SmsCode::SMS_CONFIG_NULL);
        }

        $target = new Target($data);
        if (empty($target->getPhone())) {
            SmsException::json('目标手机号码错误', SmsCode::SMS_PHONE_NULL);
        }

        if (empty($target->getContent())) {
            SmsException::json('短信内容不能为空', SmsCode::SMS_CONTENT_NULL);
        }

        // 使用的平台
        $platform = $target->getPlatform();
        if (empty($platform)) {
            $platform = $config['default'] ?? '';
        }
        // 获取平台配置
        $platform_config = $config[$platform] ?? [];
        if (empty($platform_config)) {
            SmsException::json('短信平台配置信息错误', SmsCode::SMS_PLATFORM_NULL);
        }

        $setting = new Setting($platform_config);
        $class = $setting->getClass();
        if (empty($class)) {
            switch ($platform) {
                case 'tencent':
                    $class = Target::class;
                    break;
                case 'ali':
                    $class = Ali::class;
                    break;
            }
        }
        if (!class_exists($class)) {
            SmsException::json('短信平台实例化错误', SmsCode::SMS_PLATFORM_CLASS_NULL);
        }
        // 是否指定使用那个账号
        $account = $target->getAccount();
        if (empty($account)) {
            $account = current($setting->getUse());
        }
        // 账号配置
        $account_config = $setting->getAccounts()[$account] ?? [];
        if (empty($account_config)) {
            SmsException::json('平台账号信息配置错误', SmsCode::SMS_PLATFORM_ACCOUNT_NULL);
        }

        /**
         * @var Platform $platform
         */
        $platform = new $class($account_config);
        $platform->setTarget($target);
        $platform->setConfig($account_config);

        return $platform;
    }
}